﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace ZBJF.Warranty.WebProvider.Filter
{
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class ControllerErrorLogExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                string controllerName = (string)filterContext.RouteData.Values["controller"];
                string actionName = (string)filterContext.RouteData.Values["action"];
                string msgTemplate = string.Format("在执行 controller[{0}] 的 action[{1}] 时产生异常.", controllerName, actionName);
                string error = string.Format("异常位置: {0};异常信息:{1};错误源:{2};堆栈信息:{3}", filterContext.RequestContext.HttpContext.Request.Url.ToString(), filterContext.Exception.Message, filterContext.Exception.Source, filterContext.Exception.StackTrace);
                // 写入日志
                if (!filterContext.Exception.Message.Contains("无法在发送"))
                {
                    Common.Common.LogHelper.WriteLog(msgTemplate + error, Common.Common.LogType.error);
                }
            }
            if (filterContext.Result is JsonResult)
            {
                //当结果为json时，设置异常已处理
                filterContext.ExceptionHandled = true;
            }
            else
            {
                //否则调用原始设置
                base.OnException(filterContext);
            }

        }
    }
}
